package com.xuecheng.content.service.impl;

import com.xuecheng.content.config.MinioProperties;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * @author Sober_wxy
 * @date 2022/7/23 16:57
 */
@Service
@Slf4j
public class PublishHtmlService {

        @Autowired
        private Configuration configuration;
        @Autowired
        private MinioClient minioClient;
        @Autowired
        private MinioProperties minioProperties;
        @Async("xueChengPool")
        public void publishHtml(Map preview,Long coursePubId) throws Exception {

                // 模拟网络较差的情况
                // Thread.sleep(1000);
                log.info("生成静态页面线程 = " + Thread.currentThread().getName());
                //B --生成html页面 存入minio
                // 获取模板 路径必须写全
                Template template = configuration.getTemplate("learing_article.ftl");
                // 数据
                // 工具类 模板和数据静态化处理为字符串
                String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, preview);
                // 数据流处理
                ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
                // 上传到Minio
                // 指定上传的文件位置
                String filePath = "/pages/" + coursePubId + ".html";
                PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                        .contentType("text/html")
                        .stream(inputStream, inputStream.available(), -1)
                        .bucket(minioProperties.getBucket())
                        .object(filePath)
                        .build();
                minioClient.putObject(putObjectArgs);
        }
        @Async("xueChengPool")
        public void deleteHtml(Long coursePubId){
                String url = "/pages/" + coursePubId + ".html";
                try {
                        minioClient.removeObject(RemoveObjectArgs.builder().bucket(minioProperties.getBucket()).object(url).build());
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}
